# coding=utf-8
import re
from PIL import Image, ImageDraw, ImageFont

LINE_CHAR_COUNT = 12*2  # 每行字符数：12个中文字符
TABLE_WIDTH = 4

def line_break(line):
    ret = ''
    width = 0
    for c in line:
        if len(c.encode('utf8')) == 3:  # 中文
            if LINE_CHAR_COUNT == width + 1:  # 剩余位置不够一个汉字
                width = 2
                ret += '\n' + c
            else: # 中文宽度加2，注意换行边界
                width += 2
                ret += c
        else:
            if c == '\t':
                space_c = TABLE_WIDTH - width % TABLE_WIDTH  # 已有长度对TABLE_WIDTH取余
                ret += ' ' * space_c
                width += space_c
            elif c == '\n':
                width = 0
                ret += c
            else:
                width += 1
                ret += c
        if width >= LINE_CHAR_COUNT:
            ret += '\n'
            width = 0
    if ret.endswith('\n'):
        return ret
    return ret + '\n'


output_str = "白内障人群发病年龄多见于、40岁以上，其中60-8，9岁人群中，白内障发病率高、达80%"  # 测试字符串
output_str = line_break(output_str)
split_lines = output_str.split('\n')  # 计算行数
split_lines = [var for var in split_lines if var] # 去除空数组
arr = ['，', '、', '。', ',','!',"?","？","！","-"]
print(split_lines)
for item in range(0,len(split_lines)):
    symbol = split_lines[item][0] # 获取符号
    print(symbol)
    if (symbol in arr):
        if len(split_lines) > item+1:
            split_lines[item] = split_lines[item] + split_lines[item + 1][0]
            split_lines[item + 1] = split_lines[item + 1][1:]
        split_lines[item] = split_lines[item][1:]
        split_lines[item - 1] = split_lines[item - 1] + symbol
print(split_lines)
split_lines = "\n".join(split_lines)
d_font = ImageFont.truetype('SIMLI.TTF', 20)
image = Image.open("bg.jpeg")
draw_table = ImageDraw.Draw(im=image)
draw_table.text(xy=(100, 100), text=split_lines, fill=255, font= d_font, spacing=4)  # 文字位置，内容，字体
image.show()  # 直接显示图片
# image.save('comments.png', 'PNG')  # 保存在当前路径下，格式为PNG
image.close()
